import { changeUserInfo, outLogin} from '@/services/ant-design-pro/api';
import { EditOutlined, LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import {Avatar, Form, Menu, Modal, Select, Spin, Input, message} from 'antd';
import type { ItemType } from 'antd/lib/menu/hooks/useItems';
import { stringify } from 'querystring';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, {useCallback, useState} from 'react';
import { history, useModel } from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { FALLBACK_LOGO } from '@/constant';



export type GlobalHeaderRightProps = {
  menu?: boolean;
};

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  await outLogin();
  const { query = {}, search, pathname } = history.location;
  const { redirect } = query;
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login' && !redirect) {
    history.replace({
      pathname: '/user/login',
      search: stringify({
        redirect: pathname + search,
      }),
    });
  }
};



const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  const showRoleModal = () => {
    if (initialState && initialState.currentUser) {
      const userInfo = initialState.currentUser;
      setIsModalVisible(true);
      form.setFieldsValue({
        userName: userInfo.userName,
        avatarUrl: userInfo.avatarUrl,
        phone: userInfo.phone,
        email: userInfo.email,
        gender: userInfo.gender,
      });
    }
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      //@ts-ignore
      values.userAccount = initialState.currentUser.userAccount;
      console.log('Form values:', values);
      const response = await changeUserInfo(values);
      if (response) {
        message.success('用户信息更新成功！');
        setIsModalVisible(false); // 关闭模态框
      } else {
        message.error('信息更新失败');
      }

    } catch (error) {
      message.error('用户信息更新失败');
    }
  };


  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        setInitialState((s) => ({ ...s, currentUser: undefined }));
        loginOut();
        return;
      }
      if (key === 'changeinfo') {
        showRoleModal();
        return;
      }
      history.push(`/account/${key}`);
    },
    [setInitialState],
  );

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }


  const { currentUser } = initialState;

  if (!currentUser || !currentUser.userAccount) {
    return loading;
  }

  const menuItems: ItemType[] = [
    ...(menu
      ? [
          {
            key: 'center',
            icon: <UserOutlined />,
            label: '个人中心',
          },
          {
            key: 'settings',
            icon: <SettingOutlined />,
            label: '个人设置',
          },
          {
            type: 'divider' as const,
          },
        ]
      : []),
    {
      key: 'changeinfo',
      icon: <EditOutlined />,
      label: '修改信息',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick} items={menuItems} />
  );


  return (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar
            size="small"
            className={styles.avatar}
            src={currentUser.avatarUrl ? currentUser.avatarUrl : FALLBACK_LOGO}
            alt="avatar"
          />
          <span className={`${styles.name} anticon`}>
            {currentUser?.userName ? currentUser?.userName : '用户'}
          </span>
        </span>
      </HeaderDropdown>
      <Modal
        title="修改用户信息"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="userName"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item name="avatarUrl" label="头像">
            <Input />
          </Form.Item>
          <Form.Item name="email" label="邮箱" rules={[{ type: 'email', message: '请输入正确的邮箱' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="phone" label="手机号">
            <Input />
          </Form.Item>
          <Form.Item name="gender" label="性别">
            <Select>
              <Select.Option value="0">男</Select.Option>
              <Select.Option value="1">女</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AvatarDropdown;
